<template>
    <div>
        <!-- 面包屑区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <!-- 头部按钮以及搜索区域 -->
            <el-row :gutter="20">
              <el-col :span="8">
                <el-input v-model="queryInfo.query" placeholder="请输入内容" clearable>
                    <el-button slot="append" icon="el-icon-search" @click="searchUserInfo"></el-button>
                </el-input>
              </el-col>
              <el-col :span="4">
                <el-button type="primary" @click="addUserDialog">添加用户</el-button>
              </el-col>
            </el-row>
            <!-- 表格区域 -->
            <el-table :data="userList" style="width: 100%" border stripe>
                <el-table-column type="index" label="#" ></el-table-column>
                <el-table-column  prop="username" label="姓名" ></el-table-column>
                <el-table-column  prop="email" label="邮箱"></el-table-column>
                <el-table-column  prop="mobile" label="电话"></el-table-column>
                <el-table-column  prop="role_name" label="角色"></el-table-column>
                <el-table-column  prop="mg_state" label="状态">
                  <template slot-scope="scope">
                    <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)"
                    active-color="#13ce66">
                    </el-switch>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                  <template slot-scope="scope">
                    <el-button size="mini" type="primary"  icon="el-icon-edit" @click="editUserInfo(scope.row.id)"></el-button>
                    <el-button  size="mini"  type="danger"  icon="el-icon-delete" @click="deleteUserInfo(scope.row.id)"></el-button>
                    <el-tooltip effect="dark" content="分配角色" placement="top">
                      <el-button  size="mini"  type="warning"  icon="el-icon-setting" @click="allotRoles(scope.row)"></el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
            </el-table>
            <!-- 分页功能 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryInfo.pagenum"
              :page-sizes="[1, 2, 5, 10]"
              :page-size="queryInfo.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户的对话框 -->
        <el-dialog title="添加用户" :visible.sync="addUserDialogVisible"
          width="50%" @close="closeAddUserForm">
          <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="70px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addUserForm.username"></el-input>
            </el-form-item>
             <el-form-item label="密码" prop="password">
              <el-input v-model="addUserForm.password"></el-input>
            </el-form-item>
             <el-form-item label="邮箱" prop="email">
              <el-input v-model="addUserForm.email"></el-input>
            </el-form-item>
             <el-form-item label="手机号" prop="mobile">
              <el-input v-model="addUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addUserDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitAddUserForm">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改用户的对话框 -->
        <el-dialog title="修改用户信息" :visible.sync="editUserDialogVisible"
          width="50%">
          <el-form :model="editUserForm" :rules="editUserFormRules" ref="editUserFormRef" label-width="70px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editUserForm.username" disabled></el-input>
            </el-form-item>
             <el-form-item label="邮箱" prop="email">
              <el-input v-model="editUserForm.email"></el-input>
            </el-form-item>
             <el-form-item label="手机号" prop="mobile">
              <el-input v-model="editUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editUserDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitEditUserForm">确 定</el-button>
          </span>
        </el-dialog>
                <!-- 分配角色的对话框 -->
        <el-dialog title="分配角色" :visible.sync="allotRolesDialogVisible"
          width="50%" @close="setRoleDialogClosed">
          <div>
            <p>当前的用户：{{userInfo.name}}</p>
            <p>当前的角色：{{userInfo.role_name}}</p>
            <p>分配新角色：
              <el-select v-model="selectRoleId" placeholder="请选择角色">
                <el-option v-for="item in rolesList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
                </el-option>
              </el-select>
            </p>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="allotRolesDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitAllotRoles">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
  data () {
    // 自定义校验规则
    var validateMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入合法的手机号'))
      }
    }
    var validateEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入合法的邮箱'))
      }
    }
    return {
      // 得到用户列表的
      queryInfo: {
        query: '',
        pagenum: 2,
        pagesize: 1
      },
      // 总记录数目
      total: 0,
      // 得到获取的用户列表
      userList: [],
      // 控制添加用户的对话框显示和隐藏
      addUserDialogVisible: false,
      // 添加用户的对话框的表单
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单的验证规则
      addUserFormRules: {
        username: [
          { required: true, message: '请选择用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }

        ]
      },
      // 控制修改用户的对话框显示和隐藏
      editUserDialogVisible: false,
      // 修改用户的对话框的表单
      editUserForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 修改用户表单的验证规则
      editUserFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }

        ]
      },
      // 分配角色的对话框
      allotRolesDialogVisible: false,
      allotRolesForm: {},
      // 获取分配角色对话框中的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已经选中的角色id
      selectRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取用户列表的数据
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('获取用户列表失败')
      } else {
        this.userList = res.data.users
        this.total = res.data.total
      }
    },
    // 编辑用户列表
    async editUserInfo (rowId) {
      const { data: res } = await this.$http.get(`users/${rowId}`)
      if (res.meta.status !== 200) {
        this.$message.error('查询失败')
      } else {
        this.editUserDialogVisible = true
        this.editUserForm = res.data
      }
    },
    // 删除用户列表表格
    async deleteUserInfo (rowId) {
      // $confirm也需要按需导入，同时返回的是一个promise
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => {
        return error
      })
      // 如果用户确认删除，返回字符串为confirm。否则返回为cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      } else {
        const { data: res } = await this.$http.delete(`users/${rowId}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除用户失败')
        } else {
          this.$message.success('删除用户成功')
          this.getUserList()
        }
      }
    },
    // 分页中改变
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 分页中改变
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听用户状态改变
    async changeUserState (row) {
      const { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      if (res.meta.status !== 200) {
        // 更新失败，要将状态变回原来的样子
        row.mg_state = !row.mg_state
        this.$message.error('用户状态更新失败')
      } else {
        this.$message.success('用户状态更新成功')
      }
    },
    // 实现搜索功能
    searchUserInfo () {
      this.getUserList()
    },
    // 点击添加用户按钮，弹出对话框
    addUserDialog () {
      this.addUserDialogVisible = true
    },
    // 监听添加用户对话框的关闭事件，清空表单
    closeAddUserForm () {
      this.$refs.addUserFormRef.resetFields()
    },
    // 提交添加用户的表单，点击确定按钮
    submitAddUserForm () {
      this.$refs.addUserFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('users', this.addUserForm)
          if (res.meta.status !== 201) {
            this.$message.error('添加失败')
          } else {
            this.$message.success('添加成功')
            this.addUserDialogVisible = false
            this.getUserList()
          }
        } else {
          return false
        }
      })
    },
    // 提交添加用户的表单，点击确定按钮
    submitEditUserForm () {
      this.$refs.editUserFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(`users/${this.editUserForm.id}`,
            {
              email: this.editUserForm.email,
              mobile: this.editUserForm.mobile
            })
          if (res.meta.status !== 200) {
            this.$message.error('修改失败')
          } else {
            this.$message.success('修改成功')
            this.editUserDialogVisible = false
            this.getUserList()
          }
        } else {
          return false
        }
      })
    },
    // 点击分配角色按钮，弹出对话框
    async allotRoles (row) {
      this.allotRolesDialogVisible = true
      this.userInfo = row
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      } else {
        console.log(res)
        this.rolesList = res.data
      }
    },
    // 点击确定按钮，成功分配角色
    async submitAllotRoles () {
      if (!this.selectRoleId) {
        this.$message.error('请选择要分配的角色')
      } else {
        const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectRoleId })
        if (res.meta.status !== 200) {
          this.$message.error('分配角色失败')
        } else {
          this.$message.success('更新成功')
          this.getUserList()
          this.allotRolesDialogVisible = false
        }
      }
    },
    // 监听分配角色对话框的关闭，清空对话框里面的数据
    setRoleDialogClosed () {
      this.userInfo = {}
      this.selectRoleId = ''
    }

  }
}
</script>
<style scoped>
.el-breadcrumb{
    margin-bottom: 15px
}
.el-card{
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.5) !important
}
.el-row{
    margin-bottom: 15px
}
</style>
